#region

using System;
using DomainModel.Infrastructure.Mappings;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

#endregion

namespace DomainModel.Utils
{
    public class NHibernateSessionFactory
    {
        protected virtual Configuration Configuration { get; private set; }


        public ISessionFactory CreateSessionFactory()
        {
            try
            {
                Configuration = BuildConfiguration();
                ISessionFactory sessionFactory = Configuration.BuildSessionFactory();
                SchemaExport(Configuration);
                return sessionFactory;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
        }

        private Configuration BuildConfiguration()
        {
            PostgreSQLConfiguration config = PostgreSQLConfiguration.Standard
                .ConnectionString(c => c
                                           .Host("localhost")
                                           .Port(5432)
                                           .Database("plumber")
                                           .Username("postgres")
                                           .Password("start")).ShowSql();

            FluentConfiguration configuration = Fluently
                .Configure()
                .Database(config)
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<MessageAssemblyMap>());

            return configuration.BuildConfiguration();
        }

        protected void SchemaExport(Configuration config)
        {
            // uncomment next line to auto-create db schema
             // new SchemaExport(config).Execute(true, true, false);
        }
    }
}